<template>
  <div class="core-analysis">
    <!-- Title section -->
    <div class="header-section">
      <h1 class="main-title">Core Data Analysis</h1>
      <p class="sub-title">
        This dashboard page shows some of the company's key sales data, including sales, proft, number of orders,
        volume, number
        of customers, etc.
      </p>
    </div>

    <!-- Content section -->
    <div class="content-section">
      <!-- Filter section -->
      <div class="filter-section">
        <el-form :inline="true" :model="filterForm">
          <el-form-item>
            <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="to"
              start-placeholder="Start Date"
              end-placeholder="End Date"
              style="width: 260px" />
          </el-form-item>
          <el-form-item>
            <el-select v-model="filterForm.category" placeholder="Product Category" clearable>
              <el-option v-for="item in categories" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="filterForm.city" placeholder="Select City" clearable>
              <el-option v-for="item in cities" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="filterForm.shopId" placeholder="Shop ID" clearable>
              <el-option v-for="item in shops" :key="item" :label="`Shop ${item}`" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="filterForm.gender" placeholder="Gender" clearable>
              <el-option label="Male" value="male" />
              <el-option label="Female" value="female" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="filterForm.ageRange" placeholder="Age Range" clearable>
              <el-option v-for="item in ageRanges" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button-group>
              <el-button type="primary" @click="handleFilter">
                <el-icon>
                  <Search />
                </el-icon>
                Filter
              </el-button>
              <el-button @click="resetFilter">
                <el-icon>
                  <Refresh />
                </el-icon>
                Reset
              </el-button>
            </el-button-group>
          </el-form-item>
        </el-form>
      </div>

      <!-- KPI cards -->
      <div class="kpi-wrapper">
        <div class="kpi-section">
          <el-row :gutter="10" justify="space-evenly" style="flex-wrap: nowrap;">
            <el-col :span="4.2" v-for="(kpi, index) in kpiData" :key="index">
              <el-card class="kpi-card" shadow="hover">
                <div class="kpi-title">{{ kpi.title }}</div>
                <div class="kpi-value">{{ kpi.value }}</div>
                <div class="kpi-trends">
                  <div class="trend-item">
                    <div class="trend-label">Week-over-Week</div>
                    <div :class="['trend-value', kpi.weekOnWeek > 0 ? 'up' : 'down']">
                      <el-icon>
                        <CaretTop v-if="kpi.weekOnWeek > 0" />
                        <CaretBottom v-else />
                      </el-icon>
                      {{ Math.abs(kpi.weekOnWeek) }}%
                    </div>
                  </div>
                  <div class="trend-item">
                    <div class="trend-label">Day-over-Day</div>
                    <div :class="['trend-value', kpi.dayOnDay > 0 ? 'up' : 'down']">
                      <el-icon>
                        <CaretTop v-if="kpi.dayOnDay > 0" />
                        <CaretBottom v-else />
                      </el-icon>
                      {{ Math.abs(kpi.dayOnDay) }}%
                    </div>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- Charts section -->
      <div class="charts-section">
        <el-row :gutter="20">
          <el-col :span="12" v-for="(chart, index) in computedCharts" :key="index">
            <el-card class="chart-card" shadow="hover">
              <div class="chart-title">
                {{ chart.title }}
                <el-icon 
                  class="chart-type-switch" 
                  @click="() => toggleChartType(index)"
                  :title="getNextTypeTitle(chartTypes[index])">
                  <component :is="getChartTypeIcon(chartTypes[index])" />
                </el-icon>
              </div>
              <ECharts :options="chart.options" height="350px" />
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed, reactive } from 'vue'
import { CaretTop, CaretBottom, Search, Refresh, TrendCharts, DataLine, Histogram } from '@element-plus/icons-vue'
import ECharts from '@/components/ECharts.vue'
import { getCoreAnalysis, getFilterOptions } from '@/api'
import { ElMessage } from 'element-plus'

const props = defineProps({
  filterParams: Object
})

// 筛选表单数据
const filterForm = reactive({
  dateRange: [],  // 不设置默认日期范围
  category: '',
  city: '',
  shopId: '',
  gender: '',
  ageRange: ''
})

// 筛选选项数据
const categories = ref([])
const cities = ref([])
const shops = ref([])
const ageRanges = ref([])

// 处理筛选
const handleFilter = async () => {
  try {
    await fetchData()
  } catch (error) {
    ElMessage.error('筛选数据失败，请重试')
  }
}

// 重置筛选
const resetFilter = () => {
  filterForm.dateRange = []
  filterForm.category = ''
  filterForm.city = ''
  filterForm.shopId = ''
  filterForm.gender = ''
  filterForm.ageRange = ''
  fetchData()
}

// 获取筛选选项数据
const loadFilterOptions = async () => {
  try {
    const options = await getFilterOptions()
    categories.value = options.categories
    cities.value = options.cities
    shops.value = options.shops
    ageRanges.value = options.ageRanges
  } catch (error) {
    ElMessage.error('Network error, please try again later')
  }
}

// KPI 数据
const kpiData = ref([])

// 图表配置
const chartData = ref({
  months: [],
  sales: [],
  profit: [],
  orders: [],
  volume: [],
  customers: []
})

// 图表类型数组
const CHART_TYPES = ['line', 'area', 'bar']

// 图表类型状态
const chartTypes = ref(['line', 'line', 'line', 'line'])

// 获取下一个类型的提示文字
const getNextTypeTitle = (currentType) => {
  switch (currentType) {
    case 'line': return '切换为面积图'
    case 'area': return '切换为柱状图'
    case 'bar': return '切换为折线图'
    default: return '切换图表类型'
  }
}

// 获取当前图表类型的图标
const getChartTypeIcon = (type) => {
  switch (type) {
    case 'line': return TrendCharts
    case 'area': return DataLine
    case 'bar': return Histogram
    default: return TrendCharts
  }
}

// 切换图表类型
const toggleChartType = (index) => {
  const currentType = chartTypes.value[index]
  const currentIndex = CHART_TYPES.indexOf(currentType)
  const nextIndex = (currentIndex + 1) % CHART_TYPES.length
  chartTypes.value[index] = CHART_TYPES[nextIndex]
}

// 计算图表配置
const computedCharts = computed(() => {
  return charts.value.map((chart, index) => ({
    ...chart,
    options: {
      ...chart.options,
      series: chart.options.series.map(series => getSeriesConfig(chartTypes.value[index], series.data, series.name))
    }
  }))
})

// 修改图表配置，添加图表类型相关的配置
const getSeriesConfig = (type, data, name) => {
  const baseConfig = {
    name,
    data,
    symbolSize: 8
  }

  switch (type) {
    case 'bar':
      return {
        ...baseConfig,
        type: 'bar',
      }
    case 'area':
      return {
        ...baseConfig,
        type: 'line',
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: name === 'Profit' ? 'rgba(103, 194, 58, 0.6)' :
                     name === 'Order Count' ? 'rgba(230, 162, 60, 0.6)' :
                     name === 'Sales Volume' ? 'rgba(245, 108, 108, 0.6)' :
                     name === 'Customer Count' ? 'rgba(144, 147, 153, 0.6)' : 'rgba(64, 158, 255, 0.6)'
            }, {
              offset: 1,
              color: name === 'Profit' ? 'rgba(103, 194, 58, 0.1)' :
                     name === 'Order Count' ? 'rgba(230, 162, 60, 0.1)' :
                     name === 'Sales Volume' ? 'rgba(245, 108, 108, 0.1)' :
                     name === 'Customer Count' ? 'rgba(144, 147, 153, 0.1)' : 'rgba(64, 158, 255, 0.1)'
            }]
          }
        }
      }
    case 'line':
    default:
      return {
        ...baseConfig,
        type: 'line',
        smooth: true,
        lineStyle: {
          width: 3
        },
        showSymbol: true
      }
  }
}

// 获取分析数据
const fetchData = async () => {
  try {
    const params = {
      startDate: filterForm.dateRange?.[0] || null,
      endDate: filterForm.dateRange?.[1] || null,
      category: filterForm.category || null,
      city: filterForm.city || null,
      shopId: filterForm.shopId || null,
      gender: filterForm.gender || null,
      ageRange: filterForm.ageRange || null
    }

    const data = await getCoreAnalysis(params)
    if (data?.kpiData) {
      // 更新KPI数据
      kpiData.value = [
        {
          title: 'Total Sales',
          value: data.kpiData.totalSales,
          weekOnWeek: data.kpiData.salesWeekOnWeek.toFixed(2),
          dayOnDay: data.kpiData.salesDayOnDay.toFixed(2)
        },
        {
          title: 'Profit',
          value: data.kpiData.totalProfit,
          weekOnWeek: data.kpiData.profitWeekOnWeek.toFixed(2),
          dayOnDay: data.kpiData.profitDayOnDay.toFixed(2)
        },
        {
          title: 'Number of Orders',
          value: formatNumber(data.kpiData.orderCount),
          weekOnWeek: data.kpiData.orderWeekOnWeek.toFixed(2),
          dayOnDay: data.kpiData.orderDayOnDay.toFixed(2)
        },
        {
          title: 'Sales Volume',
          value: formatNumber(data.kpiData.salesVolume),
          weekOnWeek: data.kpiData.volumeWeekOnWeek.toFixed(2),
          dayOnDay: data.kpiData.volumeDayOnDay.toFixed(2)
        },
        {
          title: 'Number of Customers',
          value: formatNumber(data.kpiData.customerCount),
          weekOnWeek: data.kpiData.customerWeekOnWeek.toFixed(2),
          dayOnDay: data.kpiData.customerDayOnDay.toFixed(2)
        }
      ]

      // 更新图表数据
      if (data.chartData) {
        chartData.value = {
          months: data.chartData.months || [],
          sales: data.chartData.sales || [],
          profit: data.chartData.profits || [],
          orders: data.chartData.orders || [],
          volume: data.chartData.volumes || [],
          customers: data.chartData.customers || []
        }
      }
    }
  } catch (error) {
    ElMessage.error('获取分析数据失败，请重试')
  }
}

// 销售利润图表配置
const salesProfitOptions = computed(() => ({
  color: ['#409EFF', '#67C23A'],
  tooltip: {
    trigger: 'axis',
    formatter: function (params) {
      return params.map(param => {
        return `${param.seriesName}: ${formatNumber(param.value)}`
      }).join('<br/>')
    }
  },
  legend: {
    data: ['Total Sales', 'Profit'],
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    top: '40px',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: chartData.value.months,
    axisLabel: {
      formatter: (value) => value.charAt(0) + value.slice(1).toLowerCase()
    }
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      formatter: (value) => `${formatNumber(value)}`
    }
  },
  series: [
    {
      name: 'Total Sales',
      type: 'line',
      smooth: true,
      data: chartData.value.sales,
      symbolSize: 8,
      lineStyle: {
        width: 3
      },
      areaStyle: {
        opacity: 0.1
      }
    },
    {
      name: 'Profit',
      type: 'line',
      smooth: true,
      data: chartData.value.profit,
      symbolSize: 8,
      lineStyle: {
        width: 3,
        type: 'dashed'
      }
    }
  ]
}))

// 订单数量图表配置
const ordersOptions = computed(() => ({
  color: ['#E6A23C'],
  tooltip: {
    trigger: 'axis',
    formatter: function (params) {
      return `${params[0].seriesName}: ${formatNumber(params[0].value)}`
    }
  },
  legend: {
    data: ['Order Count'],
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    top: '40px',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: chartData.value.months,
    axisLabel: {
      formatter: (value) => value.charAt(0) + value.slice(1).toLowerCase()
    }
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      formatter: (value) => `${formatNumber(value)}`
    }
  },
  series: [
    {
      name: 'Order Count',
      type: 'line',
      smooth: true,
      data: chartData.value.orders,
      symbolSize: 8,
      lineStyle: {
        width: 3
      },
      areaStyle: {
        opacity: 0.1
      }
    }
  ]
}))

// 销售量趋势图表配置
const volumeOptions = computed(() => ({
  color: ['#F56C6C'],
  tooltip: {
    trigger: 'axis',
    formatter: function (params) {
      return `${params[0].seriesName}: ${formatNumber(params[0].value)}`
    }
  },
  legend: {
    data: ['Sales Volume'],
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    top: '40px',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: chartData.value.months,
    axisLabel: {
      formatter: (value) => value.charAt(0) + value.slice(1).toLowerCase()
    }
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      formatter: (value) => `${formatNumber(value)}`
    }
  },
  series: [
    {
      name: 'Sales Volume',
      type: 'line',
      smooth: true,
      data: chartData.value.volume,
      symbolSize: 8,
      lineStyle: {
        width: 3
      },
      areaStyle: {
        opacity: 0.1
      }
    }
  ]
}))

// 客户数量趋势图表配置
const customersOptions = computed(() => ({
  color: ['#909399'],
  tooltip: {
    trigger: 'axis',
    formatter: function (params) {
      return `${params[0].seriesName}: ${formatNumber(params[0].value)}`
    }
  },
  legend: {
    data: ['Customer Count'],
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    top: '40px',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: chartData.value.months,
    axisLabel: {
      formatter: (value) => value.charAt(0) + value.slice(1).toLowerCase()
    }
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      formatter: (value) => `${formatNumber(value)}`
    }
  },
  series: [
    {
      name: 'Customer Count',
      type: 'line',
      smooth: true,
      data: chartData.value.customers,
      symbolSize: 8,
      lineStyle: {
        width: 3
      },
      areaStyle: {
        opacity: 0.1
      }
    }
  ]
}))

// 监听筛选参数变化
watch(() => props.filterParams, (newParams) => {
  // 根据筛选参数更新数据
  fetchData()
  // 这里添加数据更新逻辑
}, { deep: true })

// 在 watch 中监听图表类型变化
watch(chartTypes, (newTypes) => {
  charts.value = charts.value.map((chart, index) => ({
    ...chart,
    options: {
      ...chart.options,
      series: chart.options.series.map(series => getSeriesConfig(newTypes[index], series.data, series.name))
    }
  }))
}, { deep: true })

onMounted(() => {
  loadFilterOptions()
  fetchData()  // 初始加载数据
})

// 添加 charts 数组用于图表循环
const charts = computed(() => [
  {
    title: 'Total sales with profit',
    options: salesProfitOptions.value
  },
  {
    title: 'Number of orders',
    options: ordersOptions.value
  },
  {
    title: 'Sales volume',
    options: volumeOptions.value
  },
  {
    title: 'Number of customers',
    options: customersOptions.value
  }
])

// 格式化货币
const formatCurrency = (value) => {
  if (!value) return '0'
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
    minimumFractionDigits: 2
  }).format(value)
}

// 格式化数字
const formatNumber = (value) => {
  if (!value) return '0'
  return new Intl.NumberFormat('zh-CN').format(value)
}
</script>

<style scoped>
.core-analysis {
  width: calc(100vw - 400px);
  height: 100%;
  overflow-y: auto;
  background-color: #f5f7fa;
}

.header-section {
  padding: 24px;
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
}

.main-title {
  font-size: 24px;
  font-weight: 600;
  color: #1f2f3d;
  margin-bottom: 8px;
}

.sub-title {
  font-size: 14px;
  color: #5e6d82;
  margin: 0;
}

.content-section {
  padding: 24px;
}

.filter-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.filter-section :deep(.el-form--inline) {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.filter-section :deep(.el-form-item) {
  margin-right: -6px;
  margin-bottom: 0;
}

.filter-section :deep(.el-select) {
  width: 140px;
}

.filter-section :deep(.el-button-group) {
  display: flex;
  gap: 8px;
}

.kpi-wrapper {
  background-color: #fff;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 20px;
}

.kpi-section {
  margin-bottom: 0;
}

.kpi-card {
  padding: 0 10px;
  background-color: #F8FAFC;
  border: 1px solid #E4E7ED;
}

.kpi-card:hover {
  background-color: #F2F6FC;
  border-color: #DCDFE6;
}

.kpi-title {
  white-space: nowrap;
  font-size: 16px;
  color: #409EFF;
  margin-bottom: 12px;
  font-weight: 500;
  padding-top: 20px;
}

.kpi-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 24px;
}

.kpi-trends {
  padding-bottom: 10px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.trend-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.trend-label {
  width: 107px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 14px;
  color: #909399;
}

.trend-value {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
}

.trend-value.up {
  color: #f56c6c;
}

.trend-value.down {
  color: #67c23a;
}

.charts-section .chart-card {
  margin-bottom: 20px;
}

.chart-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
}

.chart-type-switch {
  cursor: pointer;
  color: #909399;
  font-size: 18px;
}

.chart-type-switch:hover {
  color: #409EFF;
  background-color: #ecf5ff;
}

:deep(.el-card) {
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

:deep(.el-card:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-card__body) {
  padding: 0;
}
</style>